use sea_orm_migration::prelude::*;

use crate::{
    m20240806_000001_create_account_group::AccountGroup, m20240806_000001_create_role_table::Role,
    m20240806_000001_create_user_table::User,
};

pub struct Migration;

impl MigrationName for Migration {
    fn name(&self) -> &str {
        "m20240806_000001_create_user_role_table"
    }
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    // Define how to apply this migration: Create the table.
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(UserRole::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(UserRole::Id).big_integer().primary_key())
                    .col(
                        ColumnDef::new(UserRole::AccountGroupId)
                            .big_integer()
                            .not_null(),
                    )
                    .col(ColumnDef::new(UserRole::UserId).big_integer().not_null())
                    .col(ColumnDef::new(UserRole::RoleId).big_integer().not_null())
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_user_role_account_group")
                            .from(UserRole::Table, UserRole::AccountGroupId)
                            .to(AccountGroup::Table, AccountGroup::Id),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_user_role_role")
                            .from(UserRole::Table, UserRole::RoleId)
                            .to(Role::Table, Role::Id),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_user_role_user")
                            .from(UserRole::Table, UserRole::UserId)
                            .to(User::Table, User::Id),
                    )
                    .index(
                        // Creates composite unique key.
                        Index::create()
                            .unique()
                            .name("uk_user_role")
                            .col(UserRole::AccountGroupId)
                            .col(UserRole::UserId)
                            .col(UserRole::RoleId),
                    )
                    .to_owned(),
            )
            .await
    }

    // Define how to rollback this migration: Drop the table.
    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(UserRole::Table).to_owned())
            .await
    }
}

#[derive(Iden)]
pub enum UserRole {
    Table,
    Id,
    AccountGroupId,
    UserId,
    RoleId,
}
